package elastic

import (
	"../model"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/olivere/elastic"
	"strings"
)

//根据索引查询文档总数
func QueryCount(eindex string) int64 {
	client, _ := ESClient()
	defer client.Stop()
	res, err := client.Search(eindex).FetchSource(false).Do(context.Background())
	FailOnErr(err, "get count err")
	fmt.Println(res.TotalHits())
	return res.TotalHits()
}

func CreateIndexMapping(eindex, etype, emapping string) error {
	client, err := ESClient()
	FailOnErr(err, "es client err")
	exists, err := client.IndexExists(eindex).Do(context.Background())
	FailOnErr(err, "something err")
	if !exists {
		fmt.Println("Index不存在，开始创建索引")
		createIndex, err := client.CreateIndex(eindex).Body(emapping).Do(context.Background())
		FailOnErr(err, "create mapping err")
		if !createIndex.Acknowledged {
			return errors.New("create index:" + eindex + ", not Ack nowledged")
		}
		fmt.Println("create index ok")
		return nil
	} else {
		fmt.Println("Index存在，开始修改索引")
		putresp, err := client.PutMapping().Index(eindex).BodyString(emapping).Do(context.Background())
		FailOnErr(err, "create mapping err ")
		if !putresp.Acknowledged {
			return errors.New("create mapping fail, esIndexName:" + eindex + ", esTypeName:" + etype + ", not Ack nowledged")
		}
		return err
	}
}

//查询全部
func QuerySearchAll(eindex string, size, page int) *elastic.SearchResult {
	var res *elastic.SearchResult
	var err error
	res, err = client.Search(eindex).
		//Type("group_save").
		Size(size).
		From((page - 1) * size).
		Do(context.Background())
	FailOnErr(err, "search err")
	printResult(res, err)
	return res
}

//打印查询数据
func printResult(res *elastic.SearchResult, err error) (docs []model.Coolq) {
	if err != nil {
		print(err.Error())
		return
	}
	for _, item := range res.Hits.Hits {
		var cq model.Coolq
		json.Unmarshal(*item.Source., &cq)
		docs = append(docs, cq)
		//fmt.Println(cq)
		userInfo := strings.ReplaceAll(cq.UserInfo, "'", "\"")
		var user model.UserInfo
		json.Unmarshal([]byte(userInfo), &user)
		fmt.Println(user)
	}
	return
}
